# coding=utf8
from settings import ENVIRON, PATH_LOG, PATH_FILES, DEBUG
from tools.tianrui_tools import analy_re_search


def generate_spider_cmd(name):
    if ENVIRON == "local":
        cmd = "scrapy crawl {name}".format(name=name)
    else:
        cmd = "scrapy crawl {name} -s LOG_FILE={}/{name}.log".format(PATH_LOG, name=name)

    return cmd


def parse_decorator(func):
    """
    爬虫程序parse的装饰器
    :param func: *args, **kwargs
    :return:
    """
    def implement(self, response):
        try:
            if DEBUG:
                name1 = analy_re_search(self.name, ['(.+?)_spider'], israise=False, default=self.name)
                name2 = analy_re_search(str(func), ['parse_(.+?)\s'], israise=False, default="")
                filename = PATH_FILES + "/content-{}-{}.txt".format(name1, name2)

                with open(filename, "wb") as fp:
                    fp.write(response.body)
        except Exception as error:
            self.logger.warning("DEBUG 写入文件时报错，{}，{}，{}".format(self.name, str(func), error))

        return func(self, response)

    return implement


def get_int_value(value, default=0):
    if value is None or value == "" or not value.isdigit():
        return default
    else:
        return int(value)
